//
//  USAskEditViewController.m
//  us
//
//  Created by lhx on 2025/5/25.
//

#import "USAskEditViewController.h"
#import "USTalkDetailHeadView.h"
@interface USAskEditViewController ()<UITextViewDelegate>

@property (nonatomic, strong) UIButton *titleBtn;
@property (nonatomic, strong) USTalkDetailHeadView *headView;
@property (nonatomic, strong) UITextView *answerTF;
@property (nonatomic, strong) UILabel *placeholderLabel;

@end

@implementation USAskEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupView];

    self.displayEmptySet = NO;
    
    [self reloadCharacter];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.answerTF becomeFirstResponder];
}
- (void)setupView{
 
    UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_close"] style:UIBarButtonItemStylePlain target:self action:@selector(cancelEditAction)];


    UIBarButtonItem *saveItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_gouzi"] style:UIBarButtonItemStylePlain target:self action:@selector(saveAction)];
 
    self.navigationItem.leftBarButtonItem = cancelItem;
    self.navigationItem.rightBarButtonItem = saveItem;
    
    [self.titleBtn setTitle:[NSString stringWithFormat:@"Q%li",self.talkModel.seq] forState:0];
    [self.titleBtn sizeToFit];
    self.navigationItem.titleView = self.titleBtn;
 
    UIView *contentHeader = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.jk_width, 400)];
    [contentHeader addSubview:self.headView];
    [self.headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(200);
    }];
    
    CGFloat left = self.answerTF.textContainerInset.left + self.answerTF.textContainer.lineFragmentPadding;
    CGFloat top = self.answerTF.textContainerInset.top;
    
    [contentHeader addSubview:self.answerTF];
    [self.answerTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(24 - left);
        make.right.mas_equalTo(-24);
        make.bottom.mas_equalTo(0);
        make.height.mas_equalTo(200);
    }];
    

    [self.placeholderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(left);
        make.top.mas_equalTo(top);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
    self.us_tableView.tableHeaderView = contentHeader;
 
    self.answerTF.text = self.commentModel.content?:@"";
//    if (self.answerTF.text.length > 0) {
//        self.placeholderLabel.hidden = YES;
//    }
    
    RACSignal *textSignal = [self.answerTF.rac_textSignal map:^id _Nullable(NSString * _Nullable text) {
        return @(text.length > 0);
    }];
 
    RACSignal *enableSignal = [RACSignal combineLatest:@[textSignal]
                                                 reduce:^id(NSNumber *hasText){
        return @([hasText boolValue]);
    }];

    RAC(self.placeholderLabel, hidden) = enableSignal;
    
    RAC(self.navigationItem.rightBarButtonItem, enabled) = enableSignal;
}
//- (void)textViewDidChange:(UITextView *)textView {
//    self.placeholderLabel.hidden = textView.text.length > 0;
//}
 
- (void)reloadCharacter {
    if (self.commentList.count >= 2) {
        USCommentModel *model = self.commentList.firstObject;
        if ([model.userId isEqualToString:USUser.user.userId] && model.dailyTalkCommentId.length > 0) {
            self.headView.left_c_v.alpha = 1;
        }else{
            self.headView.left_c_v.alpha = 0.5;
        }
        
        USCommentModel *model1 = self.commentList[1];
        if (![model1.userId isEqualToString:USUser.user.userId] && model1.dailyTalkCommentId.length > 0) {
            self.headView.right_c_v.alpha = 1;
        }else{
            self.headView.right_c_v.alpha = 0.5;
        }
    }
 }
- (UITextView *)answerTF {
    if (_answerTF == nil) {
        _answerTF = [[UITextView alloc]init];
        _answerTF.backgroundColor = [UIColor jk_colorWithHex:0xEFEFE8];
        _answerTF.font = [UIFont systemFontOfSize:16];
        _answerTF.delegate = self;
        
        self.placeholderLabel = [[UILabel alloc] init];
        self.placeholderLabel.text = @"要写点什么呢";
        self.placeholderLabel.textColor = [UIColor lightGrayColor];
        self.placeholderLabel.font = [UIFont systemFontOfSize:16];
        [_answerTF addSubview:self.placeholderLabel];
        
    }
    return _answerTF;
}
- (UIButton *)titleBtn{
    if (!_titleBtn) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        _titleBtn = button;
        
        UIButtonConfiguration *config = [UIButtonConfiguration plainButtonConfiguration];
        config.contentInsets = NSDirectionalEdgeInsetsMake(0, 0, 0, 0);
        config.imagePadding = 6; // 图片和文字的间距
        config.titleAlignment = UIButtonConfigurationTitleAlignmentCenter; // 文字居中
        button.titleLabel.font = [UIFont systemFontOfSize:17 weight:UIFontWeightSemibold];
        button.configuration = config;
        [button setImage:[UIImage imageNamed:@"ic_love_red"] forState:UIControlStateNormal];
    }
    return _titleBtn;
}
- (USTalkDetailHeadView *)headView {
    if (_headView == nil) {
        _headView = [USTalkDetailHeadView jk_loadInstanceFromNib];
        self.headView = _headView;
        _headView.left_c_v.character = [USUser user].character;
        _headView.right_c_v.character = [USUser user].relCharacter;
        _headView.contentLab.text = self.talkModel.talkTitle;
        
        
        NSString *dayStr = [NSDateFormatter localizedStringFromDate:[NSDate dateWithTimeIntervalSince1970:self.talkModel.gmtCreate] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
        NSString *text = [NSString stringWithFormat:@"#第%li个问题 %@",self.talkModel.seq,dayStr];
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
        NSRange seqRange = [text rangeOfString:[NSString stringWithFormat:@"%ld",self.talkModel.seq]];
        NSRange dayRange = [text rangeOfString:dayStr];
        [attributedString addAttribute:NSForegroundColorAttributeName value:UIColor.systemRedColor range:seqRange];
        [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor jk_colorWithHex:0x212121 andAlpha:0.2] range:dayRange];
        _headView.numLab.attributedText = attributedString;
        
    }
    return _headView;
}
 
- (void)cancelEditAction {
    [self dismissViewControllerAnimated:YES completion:nil];

}
- (void)saveAction {
    if (self.answerTF.text.length == 0) {
        return;
    }
    [USFeedbackTool impactSoft];

    [self.answerTF resignFirstResponder];
  
    [self sendComment];
}
 
- (void)sendComment{
 
    NSString *content = self.answerTF.text?:@"";
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:@{@"dailyTalkId":self.talkModel.dailyTalkId,@"content":content}];
    
    BOOL isEdit = NO;
    if (self.commentModel.dailyTalkCommentId.length > 0) {
        //编辑
        isEdit = YES;
        params[@"dailyTalkCommentId"] = self.commentModel.dailyTalkCommentId;
    }
    @weakify(self)
    [[EMNetWork shareManager] em_post:isEdit ? API_DailyTalkCommentEdit : API_DailyTalkCommentAdd
                               params:params
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
     @strongify(self)
        if (!api.success) {
            return;
        }
        //替换第一条数据
        self.commentModel.content = content;
        if (!isEdit) {
            USCommentModel *addModel = [USCommentModel mj_objectWithKeyValues:api.data[@"DailyTalkComment"]];
            self.commentModel.dailyTalkCommentId = addModel.dailyTalkCommentId;
            self.commentModel.gmtCreate =  (NSInteger)[[NSDate date] timeIntervalSince1970];
        }
        self.commentModel.gmtModified =  (NSInteger)[[NSDate date] timeIntervalSince1970];

        if (self.didCommentBlock) {
            self.didCommentBlock();
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:nil];
        });
    } fail:^{
        
        
    }];
}

 
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
